﻿using Core.DataAccess.Model.Project.Queue;
using Core.DataAccess.Model.Projects;
using Core.Framework.Model.Common;
using Core.Framework.Model.WebSockets;
using Core.Framework.Redis.Queue_Helper;
using Core.Framework.Util;
using Core.Framework.Util.Common;
using Core.IBusiness.IUserModule;
using Core.IBusiness.IUserModule.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Core.Framework.Redis;
using StackExchange.Redis;
using ClientInfo = Core.Framework.Model.WebSockets.ClientInfo;
using System.Net;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Http;
using Aop.Api;
using Aop.Api.Request;
using Aop.Api.Response;

namespace Core.Business.SocketModule
{
    public class SocketUsers : BaseHttpPipelineInfo,ISocketUser
    {

        IRedisHelper iRedis;

        public SocketUsers(IRedisHelper _iRedis, IHttpContextAccessor iHttp) : base(iHttp)
        {
            iRedis = _iRedis;
        }

        public ApiProjectInfo GetProjectInfo()
        {
            return this.iProjectInfo;
        }


        public MethodResult<ProjectModuleUser> GetUserInfoByToken(string token, string projectToken)
        {
            var userInfo
                = RedisQueueHelper
                    .HashGet(RedisQueueHelperParameter.ProjectSocketUserLogin, projectToken + token);

            var model = ((string) userInfo).TryToEntity<ProjectModuleUser>();

            if (model != null)
            {
                if (model.EndTime > DateTime.Now)
                    return new MethodResult<ProjectModuleUser>{ IsFinished = true, Date = model};
                else
                {

                    this.OutLogin(token,projectToken);
                    return new MethodResult<ProjectModuleUser> { IsFinished = false, Discription = "身份已过期" };
                }
            }

            return new MethodResult<ProjectModuleUser>{ IsFinished = false, Discription = "信息不存在" };
        }

        public MethodResult<ProjectModuleUser> Login(LoginByUser login)
        {
            using (var context = new ProjectSocketContext())
            {

                var userInfo =
                    context
                        .ProjectModuleUser
                        .Where(a => a.UserId == login.user && a.Pass == Md5Helper.Hash(Md5Helper.Hash(login.password)) &&
                                    a.ProjectToken == login.ApiProjectInfo.Token)
                        .FirstOrDefault();

                return this.IsLoginWsByWsParameter(context, userInfo, login);

            };
        }

        public MethodResult<ProjectModuleUser> LoginByClient(LoginByUUID login)
        {
            using (var context = new ProjectSocketContext())
            {
                var userInfo =
                    context
                        .ProjectModuleUser
                        .Where(a => a.Uuid == login.uuid && a.ProjectToken == login.ApiProjectInfo.Token)
                        .FirstOrDefault();

                var result = this.IsLoginWsByWsParameter(context, userInfo, login);

                if (!result.IsFinished)
                {
                    userInfo = new ProjectModuleUser
                    {
                        Uuid = login.uuid,
                        ProjectToken = login.ApiProjectInfo.Token,
                        Paras = login.WsParameter?.Parameter
                    };

                    var tuple = this.Reg(userInfo);

                    if (tuple.Item1)
                        return this.IsLoginWsByWsParameter(context, userInfo, login);
                    else
                        return new MethodResult<ProjectModuleUser>{ IsFinished = false, Discription = tuple.Item3 };

                }


                return result;
            }

            ;
        }

        public MethodResult<ProjectModuleUser> LoginByPhone(LoginByPhone login)
        {
            using (var context = new ProjectSocketContext())
            {

                var userInfo =
                    context
                        .ProjectModuleUser
                        .Where(a => a.Phone == login.phone && a.Pass == Md5Helper.Hash(Md5Helper.Hash(login.password)) &&
                                    a.ProjectToken == login.ApiProjectInfo.Token)
                        .FirstOrDefault();

                return this.IsLoginWsByWsParameter(context, userInfo, login);

            };
        }

        public MethodResult<ProjectModuleUser> LoginByWChat(LoginByWChat login)
        {
            using (var context = new ProjectSocketContext())
            {
                var userInfo =
                    context
                        .ProjectModuleUser
                        .Where(a => a.WxOpenid == login.wchat && a.ProjectToken == this.iProjectInfo.Token)
                        .FirstOrDefault();

                var result = this.IsLoginWsByWsParameter(context, userInfo, login);

                if (!result.IsFinished)
                {
                    userInfo = new ProjectModuleUser
                    {
                        WxOpenid = login.wchat,
                        ProjectToken = this.iProjectInfo.Token
                    };

                    var tuple = this.Reg(userInfo);

                    if (tuple.Item1)
                        return this.IsLoginWsByWsParameter(context, userInfo, login);

                }

                return result;
            };
        }

        public MethodResult<ProjectModuleUser> LoginByKey(int userID, string projectToken, int hour)
        {
            using (var context = new ProjectSocketContext())
            {
                var userInfo =
                    context
                        .ProjectModuleUser
                        .Where(a => a.Id == userID && a.ProjectToken == projectToken)
                        .FirstOrDefault();

                return this.IsLoginWsByWsParameter(context, userInfo, new BaseLogin
                {
                    hour = hour,
                    ApiProjectInfo = new ApiProjectInfo {
                        Token = projectToken
                    }
                });
            }
        }

        public MethodResult<ProjectModuleUser> LoginByClientCode(LoginByPhoneCode login)
        {
            var redisKey = RedisQueueHelperParameter.SMSMessageCode + login.token;

            var value = iRedis.GetAsync(redisKey);

            int.TryParse(value.Result, out int code);

            if (code != login.code)
            {
                return new MethodResult<ProjectModuleUser> { IsFinished = false, Discription = "验证码不正确" };
            }


            using (var context = new ProjectSocketContext())
            {
                var userInfo =
                    context
                        .ProjectModuleUser
                        .Where(a => a.Phone == login.phone && a.ProjectToken == login.ApiProjectInfo.Token)
                        .FirstOrDefault();

                try
                {
                    // 验证通过主动删除键值
                    iRedis.Transaction(IR => {
                        IR.SetRemove(redisKey, code);
                        return true;
                    });
                }
                catch
                {

                }

                var result = this.IsLoginWsByWsParameter(context, userInfo, login);


                if (!result.IsFinished)
                {
                    userInfo = new ProjectModuleUser
                    {
                        Phone = login.phone,
                        ProjectToken = login.ApiProjectInfo.Token
                    };

                    var tuple = this.Reg(userInfo);

                    if (tuple.Item1)
                        return this.IsLoginWsByWsParameter(context, userInfo, login);
                    else
                        return new MethodResult<ProjectModuleUser> { 
                            IsFinished = false, 
                            Discription = tuple.Item3, 
                            Date = null 
                        };

                }

                return result;
            }
        }



        /// <summary>
        /// 退出登陆 [清除登陆相关缓存信息]
        /// </summary>
        /// <param name="token"></param>
        /// <param name="projectToken"></param>
        public void OutLogin(string token, string projectToken)
        {
            // 删除用户登陆信息
            RedisQueueHelper.HashDelete(RedisQueueHelperParameter.ProjectSocketUserLogin,
                projectToken + token);
            // 删除上次 websocket 身份信息
            RedisQueueHelper.HashDelete(RedisQueueHelperParameter.WebSocketByToken, token);
            // 删除 APi 调用令牌
            RedisQueueHelper.HashDelete(RedisQueueHelperParameter.ApiClientByToken, token);
        }


        public Tuple<bool, ProjectModuleUser, string> Reg(ProjectModuleUser model)
        {
            if (model == null)
                return new Tuple<bool, ProjectModuleUser, string>(false, model, "数据为NULL");

            var result = model.IsValid(IsValidEnum.reg);

            if (!result.Item1)
                return new Tuple<bool, ProjectModuleUser, string>(result.Item1, model, result.Item2);

            if (string.IsNullOrWhiteSpace(model.Uuid)
                && string.IsNullOrWhiteSpace(model.Phone)
                && string.IsNullOrWhiteSpace(model.WxOpenid)
                && string.IsNullOrWhiteSpace(model.BaiduOpenid)
                && string.IsNullOrWhiteSpace(model.AliPayOpenid)
            )
            {
                return new Tuple<bool, ProjectModuleUser, string>(false, model, "请指定注册账户");
            }

            
            //using (var context = new ProjectContext())
            //{
            //    var key = context.ProjectList.Where(a => a.Token == model.ProjectToken).Select(a => a.Id).FirstOrDefault();
            //    if (key < 1)
            //        return new Tuple<bool, ProjectModuleUser, string>(false, model, "该项目不存在");
            //}

            using (var context = new ProjectSocketContext())
            {
                var userInfo =
                    context.ProjectModuleUser
                        .Where(a =>
                            (a.Phone == model.Phone && a.ProjectToken == model.ProjectToken &&
                             !string.IsNullOrWhiteSpace(model.Phone))
                            || (a.Uuid == model.Uuid && a.ProjectToken == model.ProjectToken &&
                                !string.IsNullOrWhiteSpace(model.Uuid))
                            || (a.WxOpenid == model.WxOpenid && a.ProjectToken == model.ProjectToken &&
                                !string.IsNullOrWhiteSpace(model.WxOpenid))
                            || (a.UserId == model.UserId && a.ProjectToken == model.ProjectToken &&
                                !string.IsNullOrWhiteSpace(model.UserId))
                            || (a.BaiduOpenid == model.BaiduOpenid && a.ProjectToken == model.ProjectToken &&
                                !string.IsNullOrWhiteSpace(model.BaiduOpenid))
                            || (a.BaiduOpenid == model.AliPayOpenid && a.ProjectToken == model.ProjectToken &&
                                !string.IsNullOrWhiteSpace(model.AliPayOpenid))
                        ).FirstOrDefault();

                if (userInfo?.Id > 0)
                    return new Tuple<bool, ProjectModuleUser, string>(false, model, "该账号已注册");

                if (!string.IsNullOrWhiteSpace(model.Pass))
                    model.Pass = Md5Helper.Hash(Md5Helper.Hash(model.Pass));

                model.AddTime = DateTime.Now;
                model.Token = Md5Helper.Hash($"{model.Phone}_z_%^&*");
                context.ProjectModuleUser.Add(model);
                context.SaveChanges();
                return new Tuple<bool, ProjectModuleUser, string>(true, model, "注册成功");
            }

            ;
        }

        public ProjectModuleUser UpdateUserInfo(ProjectModuleUser model)
        {
            using (var context = new ProjectSocketContext())
            {

                // 验证是否根据手机修改
                Expression<Func<ProjectModuleUser, bool>> where = null;

                where = a => a.Phone == model.Phone & a.ProjectToken == model.ProjectToken & !string.IsNullOrWhiteSpace(model.Phone);

                // 根据UUID
                where = where.Or(a => a.Uuid == model.Uuid & a.ProjectToken == model.ProjectToken & !string.IsNullOrWhiteSpace(model.Uuid));

                // 根据USERID
                where = where.Or(a => a.UserId == model.UserId & a.ProjectToken == model.ProjectToken & !string.IsNullOrWhiteSpace(model.UserId));

                // 微信OPENID
                where = where.Or(a => a.WxOpenid == model.WxOpenid & a.ProjectToken == model.ProjectToken & !string.IsNullOrWhiteSpace(model.WxOpenid));

                // 百度OPENID
                where = where.Or(a => a.BaiduOpenid == model.BaiduOpenid & a.ProjectToken == model.ProjectToken & !string.IsNullOrWhiteSpace(model.BaiduOpenid));

                var userInfo =
                    context.ProjectModuleUser
                        .Where(where)
                        .FirstOrDefault();

                if (userInfo != null)
                {
                    // 密码处理
                    if (!string.IsNullOrWhiteSpace(model.Pass))
                    {
                        model.Pass = Md5Helper.Hash(Md5Helper.Hash(model.Pass));
                    }

                    userInfo.Combine(model, "Id", "id", "AddTime", "Token", "ProjectToken");
                    context.SaveChanges();
                    return userInfo;
                }

                return null;
            };
        }


        public ProjectModuleUser UpdateUserInfoParas(int key, string userToken, string projectToken, string paras)
        {
            using (var context = new ProjectSocketContext())
            {
                var userInfo = context.ProjectModuleUser
                    .Where(a =>
                        a.Id == key && a.Token == userToken && a.ProjectToken == projectToken
                    )
                    .FirstOrDefault();

                if (userInfo != null && userInfo.Id > 0)
                {

                    userInfo.Paras = userInfo.Paras.TryCombineJObject(paras).TryToJson();
                    context.SaveChanges();
                    this.UpdateUserParas(userInfo.Token, userInfo.ProjectToken, userInfo.Paras);
                    return userInfo;
                }

                return null;

            }

            ;
        }


        public MethodResult<List<ProjectModuleUser>> GetUserInfoAll(string projectToken)
        {
            try
            {
                using (var context = new ProjectSocketContext())
                {
                    var list = context.ProjectModuleUser.Where(a => a.ProjectToken == projectToken).Select(a => new ProjectModuleUser {
                        Id = a.Id,
                        Paras = a.Paras
                    }).ToList();
                    return new MethodResult<List<ProjectModuleUser>> { IsFinished = true, Date = list };
                }
            }
            catch (Exception e)
            {
                return new MethodResult<List<ProjectModuleUser>> { IsFinished = false, Discription = e.Message };
            }
        }

        public MethodResult<List<ProjectModuleUser>> GetUserInfoAll(DateTime startTime, DateTime endTime, string search,
            string projectToken, Pagination pagination)
        {
            try
            {
                using (var context = new ProjectSocketContext())
                {

                    Expression<Func<ProjectModuleUser, bool>> where = a => a.ProjectToken == projectToken;


                    if (!string.IsNullOrWhiteSpace(search))
                    {
                        where = where.And(a => a.Phone.Contains(search) || a.Paras.Contains(search) || a.Uuid == search );
                    }

                    where = where.And(a => a.AddTime >= startTime && a.AddTime <= endTime);

                    var list = context.ProjectModuleUser
                        .Where(where)
                        .Pagination(pagination);

                    return new MethodResult<List<ProjectModuleUser>> { IsFinished = true, Date = list };
                }
            }
            catch (Exception e)
            {
                return new MethodResult<List<ProjectModuleUser>> { IsFinished = false, Discription = e.Message };
            }
        }

        #region Common

        /// <summary>
        /// 修改 Paras后更新缓存
        /// </summary>
        /// <param name="usertoken"></param>
        /// <param name="projecttoken"></param>
        /// <param name="paras"></param>
        private void UpdateUserParas(string usertoken, string projecttoken,string paras)
        {
            // 读出WS缓存
            var wsValue = (string)RedisQueueHelper.HashGet(RedisQueueHelperParameter.WebSocketByToken, usertoken);

            // 读出用户缓存
            var ueValue = (string)RedisQueueHelper.HashGet(RedisQueueHelperParameter.ProjectSocketUserLogin,projecttoken + usertoken);

            // 更新 WS信息
            if (!string.IsNullOrWhiteSpace(wsValue))
            {
                ClientInfo client = wsValue.TryToEntity<ClientInfo>();

                client.User.Parameter = client.User.Parameter.TryCombineJObject(paras).TryToJson();

                WebSocketApplication.ClientUpdateParameter(client);

                RedisQueueHelper.HashSet(RedisQueueHelperParameter.WebSocketByToken, usertoken, client.TryToJson());
            }

            // 更新 用户登陆信息
            if (!string.IsNullOrWhiteSpace(ueValue))
            {
                ProjectModuleUser userInfo = ueValue.TryToEntity<ProjectModuleUser>();
                userInfo.Paras = userInfo.Paras.TryCombineJObject(paras).TryToJson();
                RedisQueueHelper.HashSet(RedisQueueHelperParameter.ProjectSocketUserLogin, projecttoken + usertoken, userInfo.TryToJson()); 
            }

        }


        /// <summary>
        /// 用户身份处理
        /// </summary>
        /// <param name="context">数据库链接对象</param>
        /// <param name="userInfo">用户信息</param>
        /// <param name="projectToken">项目Token</param>
        /// <param name="hour">有效时间</param>
        /// <returns></returns>
        private MethodResult<ProjectModuleUser> UserInfoExec(ProjectSocketContext context, ProjectModuleUser userInfo,
            string projectToken, int hour)
        {
            if (null != userInfo && userInfo.Id > 0)
            {
                // 同一用户 只保存一个token
                this.OutLogin(userInfo.Token, projectToken);

                // 用户临时token
                userInfo.Token = Md5Helper.Hash(Guid.NewGuid().ToString());

                // 过期时间
                userInfo.EndTime = DateTime.Now.AddHours(hour);

                // 更新用户token
                context.SaveChanges();

                // 释放链接
                context.Dispose();

                // 写入缓存
                RedisQueueHelper
                    .HashSet(
                        RedisQueueHelperParameter.ProjectSocketUserLogin,
                        projectToken + userInfo.Token, userInfo.TryToJson());

                var userName = string.Empty;

                try
                {
                    userName = userInfo.Paras.TryToJObject()["userName"].ToString();
                }
                catch
                {

                }
                finally
                {
                    // 写入API身份信息
                    RedisQueueHelper.HashSet(
                        RedisQueueHelperParameter.ApiClientByToken, userInfo.Token,
                        new ApiClientInfo
                        {
                            Key = userInfo.Id,
                            UserName = userName,
                            Token = userInfo.Token,
                            EndTime = userInfo.EndTime,
                            MinOpenID = string.IsNullOrWhiteSpace(userInfo.WxOpenid) ? userInfo.AliPayOpenid : userInfo.WxOpenid
                        }.TryToJson());
                }

                return
                    new MethodResult<ProjectModuleUser>{ Date = userInfo , IsFinished = true};
            }

            return new MethodResult<ProjectModuleUser> { Discription = "用户不存在", IsFinished = false };

        }


        /// <summary>
        /// Ws登陆处理
        /// </summary>
        /// <param name="model"></param>
        /// <param name="parameter"></param>
        /// <param name="url"></param>
        /// <param name="Template"></param>
        /// <returns></returns>
        private MethodResult<ProjectModuleUser> WebSocketExec(ProjectSocketContext context,
            ProjectModuleUser model, string parameter,
            string url, string Template, int hour)
        {

            Template = Template.ToLower();

            if (null == model || model?.Id == 0)
            {
                return new MethodResult<ProjectModuleUser> { Discription = "用户不存在", IsFinished = false };
            }

            if (!WebSocketApplication.TempSubscriptions.ContainsKey(Template))
            {
                return new MethodResult<ProjectModuleUser> { Discription = "订阅的主题不存在", IsFinished = false };
            }

            // 删除用户登陆信息
            this.OutLogin(model.Token, model.ProjectToken);

            if (model.Paras != parameter && !string.IsNullOrWhiteSpace(parameter))
            {
                model.Paras = model.Paras.TryCombineJObject(parameter).TryToJson();
            }

            // 生成令牌
            model.Token = Md5Helper.Hash(Guid.NewGuid().ToString());

            // 过期时间
            model.EndTime = DateTime.Now.AddHours(hour);

            // 更新用户token
            context.SaveChanges();

            string[] Subscription;

            // 接受分组消息
            var groups = context.ProjectModuleGroupUser
                .AsNoTracking()
                .Where(a => a.UserId == model.Id.ToString() && a.ProjectToken == model.ProjectToken)
                .GroupBy(a => a.GroupKey)
                .Select(a => a.Key).ToList();

            // 接受数据
            Subscription = new string[groups.Count() + 2];

            // 接收自己相关消息
            Subscription[0] = model.Id.ToString();

            // 构造接收群组消息
            int i = 1;
            foreach (var item in groups)
            {
                Subscription[i] = $"group_{item}";
                i++;
            }

            // 订阅系统推送
            Subscription[i] = "system";

            // 释放数据库
            context.Dispose();
            


            // 构造链接数据
            ClientInfo client = new ClientInfo
            {
                Template = Template.ToLower(),
                Project = new ProjectInfo
                {
                    ProjectToken = model.ProjectToken,
                    CallUrl = url
                },
                User = new UserInfo
                {
                    Key = model.Id.ToString(),
                    Parameter = model.Paras.TryCombineJObject(parameter).TryToJson(),
                    Subscription = Subscription
                }
            };

            // 写入WS身份信息
            RedisQueueHelper.HashSet(RedisQueueHelperParameter.WebSocketByToken, model.Token, client.TryToJson());


            // 写入缓存
            RedisQueueHelper
                .HashSet(
                    RedisQueueHelperParameter.ProjectSocketUserLogin,
                    model.ProjectToken + model.Token, model.TryToJson());


            // 用户名称
            var userName = string.Empty;

            try
            {
                userName = model.Paras.TryToJObject()["userName"].ToString();
            }
            catch
            {
            }
            finally
            {
                // 写入API身份信息
                RedisQueueHelper.HashSet(
                    RedisQueueHelperParameter.ApiClientByToken, model.Token,
                    new ApiClientInfo
                    {
                        Key = client.User.Key.ToInt(),
                        UserName = userName,
                        Token = model.Token,
                        EndTime = model.EndTime,
                        MinOpenID = string.IsNullOrWhiteSpace(model.WxOpenid) ? model.AliPayOpenid : model.WxOpenid
                    }.TryToJson());
            }

            return new MethodResult<ProjectModuleUser>{ Date = model , IsFinished = true};

        }


        /// <summary>
        /// 根据 WsParameter 是否为空来确定是否登陆ws
        /// </summary>
        /// <param name="context">数据库链接</param>
        /// <param name="userInfo">用户实体</param>
        /// <param name="login">登陆实体</param>
        /// <returns></returns>
        private MethodResult<ProjectModuleUser> IsLoginWsByWsParameter(ProjectSocketContext context,
            ProjectModuleUser userInfo, BaseLogin login)
        {
            if (null != login.WsParameter && !string.IsNullOrWhiteSpace(login.WsParameter.Template))
            {
                return this.WebSocketExec(context, userInfo, login.WsParameter.Parameter, login.WsParameter.Url, login.WsParameter.Template, login.hour);
            }
            else
            {
                return this.UserInfoExec(context, userInfo, login.ApiProjectInfo.Token, login.hour);
            }
        }


        #endregion


        #region 小程序登录 SDK

        /// <summary>
        /// 微信小程序登录
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        public MethodResult<ProjectModuleUser> LoginByWChatMin(LoginByWChatMin login)
        {

            MethodResult<ProjectModuleUser> result = default;

            var parameter = $"appid={iProjectInfo.PayWChatInfo.MinAppId}&secret={iProjectInfo.PayWChatInfo.MinSecret}&grant_type=authorization_code&js_code={login.code}";

            HttpWebRequest httpWebRequest = WebRequest.Create($"{login.jsapi_link}?{parameter}") as HttpWebRequest;
            httpWebRequest.Method = "GET";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            WebResponse webResponse = httpWebRequest.GetResponse() as HttpWebResponse;
            Stream dataStream = webResponse.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
            string returnStr = reader.ReadToEnd();
            reader.Close();
            webResponse.Close();

            var dic = returnStr.TryToEntity<Dictionary<string, string>>();

            if (dic.ContainsKey("openid"))
            {
                result = this.LoginByWChat(new LoginByWChat
                {
                    wchat = dic["openid"],
                    ApiProjectInfo = this.iProjectInfo,
                    hour = login.hour,
                    WsParameter = login.WsParameter
                });
            }
            else
            {
                result = new MethodResult<ProjectModuleUser>
                {
                    IsFinished = false,
                    Date = null,
                    Discription = "获取OpenID失败"
                };
            }

            return result;

        }



        public MethodResult<ProjectModuleUser> LoginByALiMin(LoginByAliMin login) 
        {

            MethodResult<ProjectModuleUser> result = default;

            IAopClient client = new DefaultAopClient(
                "https://openapi.alipay.com/gateway.do",
                iProjectInfo.PayAliInfo.MinAppId,
                iProjectInfo.PayAliInfo.MinPrivtekey,
                "json", "1.0", "RSA2", iProjectInfo.PayAliInfo.MinPublickey, "utf-8", false);
            AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
            request.GrantType = "authorization_code";
            request.Code = login.code;

            AlipaySystemOauthTokenResponse response = client.Execute(request);

            var dic = response.Body.TryToJObject();

            try
            {
                
                var openid = dic["alipay_system_oauth_token_response"]["user_id"].ToString();

                login.code = openid;

                if (!string.IsNullOrWhiteSpace(openid))
                {

                    using (var context = new ProjectSocketContext())
                    {
                        var userInfo =
                            context
                                .ProjectModuleUser
                                .Where(a => a.AliPayOpenid == login.code && a.ProjectToken == this.iProjectInfo.Token)
                                .FirstOrDefault();

                        result = this.IsLoginWsByWsParameter(context, userInfo, login);

                        if (!result.IsFinished)
                        {
                            userInfo = new ProjectModuleUser
                            {
                                AliPayOpenid = login.code,
                                ProjectToken = this.iProjectInfo.Token
                            };

                            var tuple = this.Reg(userInfo);

                            if (tuple.Item1)
                                return this.IsLoginWsByWsParameter(context, userInfo, login);

                        }

                        return result;
                    };
                }
                else {
                    result = new MethodResult<ProjectModuleUser> {IsFinished = false, Discription = response.Body };
                }
            }
            catch (Exception e)
            {
                result = new MethodResult<ProjectModuleUser>
                {
                    IsFinished = false,
                    Date = null,
                    Discription = "获取OpenID失败"
                };
            }

            return result;
        }
        #endregion

    }
}
